package com.wlps.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wlps.bo.OrderBO;
import com.wlps.bo.OrderInfo;
import com.wlps.bo.QueryComposeBo;
import com.wlps.config.RedisService;
import com.wlps.entity.*;
import com.wlps.result.ResultPageVo;
import com.wlps.service.*;
import com.wlps.service.function.GenerateOrder;
import com.wlps.service.function.TemplateQuery;
import com.wlps.utils.PageUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Time;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class OrderCenter extends TemplateQuery<Order> implements GenerateOrder {
//    public String[] orderTypes={"普通","撤销","换货","退货","全部"};
public String[] orderStatus={"可分配\",\"缺货\",\"调度中\",\"已领货\",\"配置送完成\",\"已退货"};
//    public String[] queryTypes={"操作类型","客户名称","商品名称","商品级别","客户编号"};

    public IOrderService getOrderService() {
        return orderService;
    }

    public IClientService getClientService() {
        return clientService;
    }

    @Resource
    private IOrderService orderService;
    @Resource
    private IOrderRecordService orderRecordService;
    @Resource
    private IClientService clientService;
    @Resource
    private ICommodityOrderService commodityOrderService;
    @Resource
    private IMissionListService missionListService;

    public ICommodityService getCommodityService() {
        return commodityService;
    }

    @Resource
    private ICommodityService commodityService;
    @Resource
    private RedisService redisService;
    @Resource
    private ISysUserService iSysUserService;
    public List<Order>queryOrder(int  orderStatus){
        List<Order> orders;
        if(orderStatus==5)
            orders=orderService.list();
        else
        {
            LambdaQueryWrapper<Order> eq = new LambdaQueryWrapper<Order>().eq(Order::getOrderType, orderStatus);
            orders = orderService.list(eq);
        }
        return orders;
    }

    @Override
    public LambdaQueryWrapper<Order> changeOrderColumn(QueryComposeBo queryComposeBo) {
        String queryType = queryComposeBo.getQueryType();
        switch (queryType){
            case "操作类型":
                String queryContain = queryComposeBo.getQueryContain();
                int nowStatus=0;
                for (int i = 0; i < orderStatus.length; i++) {
                    if (queryContain.equals(orderStatus[i])){nowStatus=i;break;}
                }
                List<Long> collect = orderRecordService.list(new LambdaQueryWrapper<OrderRecord>().eq(OrderRecord::getOrderStatus, nowStatus))
                        .stream().map(OrderRecord::getId).collect(Collectors.toList());
                return new LambdaQueryWrapper<Order>().in(Order::getClientId, collect);

            case "客户名称":
                Client one = clientService.getOne(new LambdaQueryWrapper<Client>().eq(Client::getName, queryComposeBo.getQueryContain()));
                return new LambdaQueryWrapper<Order>().likeLeft(Order::getClientId, one.getId());

            case "商品名称":
                List<Long> longs = commodityOrderService.queryOrdersId(queryComposeBo.getQueryContain());
                return new LambdaQueryWrapper<Order>().in(Order::getId,longs);

            default:
                return new LambdaQueryWrapper<Order>().eq(Order::getClientId,Long.parseLong(queryComposeBo.getQueryContain()));
//            case "商品级别":

        }

    }
    public ResultPageVo<Order> getPageInfo(){
        List<Order> page = orderService.list();
        return PageUtils.getPageInfo(page);
    }
    @Transactional
    public boolean updateOrder(Order order){
        Order order1 = this.queryOrder(order.getId());
        if(order1==null)
            throw new RuntimeException("不存在该订单无法更新");
        if(order1.getOrderStatus()==1&&order.getOrderStatus()==0){
            List<OrderBO> value = (List<OrderBO>) redisService.getValue(String.valueOf(order.getId()));
            List<Long> collect = value.stream().map(OrderBO::getCommodityId).collect(Collectors.toList());
            Collection<Commodity> commodities = commodityService.listByIds(collect);
            Integer enoughCommodity = isEnoughCommodity(value, commodities);
            if(enoughCommodity==0)
                throw new RuntimeException("数据订单无法满足需求,无法配送");
        }
        OrderRecord orderRecord = new OrderRecord();
        BeanUtils.copyProperties(order,orderRecord);
        orderRecord.setOrderId(order.getId());
        orderRecord.setOperatingTime(new Date());
        orderRecordService.save(orderRecord);
        return orderService.updateById(order);
    }
    @Transactional
    public boolean deleteOrder(long id){
        if(queryOrder(id)==null)
            throw new RuntimeException("当前Id订单不存在");
        redisService.del(String.valueOf(id));
        commodityOrderService.remove(new LambdaQueryWrapper<CommodityOrder>().eq(CommodityOrder::getOrderId,id));
        orderRecordService.remove(new LambdaQueryWrapper<OrderRecord>().eq(OrderRecord::getOrderId,id));
        return orderService.removeById(id);
    }

    public Order queryOrder(long id){
        return orderService.getById(id);
    }
    public Order addOrder(List<OrderBO> orders, OrderInfo orderInfo){

        Order order = this.generateOrder(orders, orderInfo);
        orderService.save(order);
        //将订单保存到redis
        redisService.set(String.valueOf(order.getId()),orders);
        Long id = order.getId();
        List<CommodityOrder> orderRecords =new ArrayList<>();
        orders.forEach(data->{
            CommodityOrder commodityOrder = new CommodityOrder().setCommodityId(data.getCommodityId())
                    .setAmountOfGoods((long) data.getNumber())
                    .setOrderId(id);
            orderRecords.add(commodityOrder);
        });

        commodityOrderService.saveBatch(orderRecords);
        OrderRecord orderRecord = new OrderRecord();
        orderRecord.setOrderId(id);
        orderRecord.setOperatingTime(new Date());
        orderRecord.setOrderStatus(order.getOrderStatus());
        orderRecord.setOrderType(order.getOrderStatus());
        SysUser byId = iSysUserService.getById(orderInfo.getOperator());
        orderRecord.setOperator(byId.getUsername());
        orderRecordService.save(orderRecord);

        return order;
    }
    @Override
    public SFunction<Order, ?> getFinishDatColumn() {
        return Order::getFinishDate;
    }

    public List<Order> queryOrdersCompose(QueryComposeBo query) {
        return super.queryOrdersByCompose(query,orderService);
    }

    public MissionList queryMissionById(long id){
        return missionListService.getById(id);
    }

    public Integer isEnoughCommodity(List<OrderBO> orders,Collection<Commodity> commodities){
        Map<Long, Long> map = commodities.stream().collect(Collectors.toMap(Commodity::getId, Commodity::getInventory,(key1,key2)->key2));
        List<OrderBO> size = orders.stream().parallel().filter(data -> map.get(data.getCommodityId()) >= data.getNumber()).collect(Collectors.toList());
        return size.size()==orders.size()?1:0;
    }
    /**
     *
     * @param orders  订单资料
     * @return Order 生成的订单插入数据库
     */
    @Override
    public Order generateOrder(List<OrderBO> orders,OrderInfo orderInfo) {
        List<Long> collect = orders.stream().map(OrderBO::getCommodityId).collect(Collectors.toList());
        Collection<Commodity> commodities = commodityService.listByIds(collect);
        assert  commodities.size()==orders.size():"有商品不存在";
        int orderStatus=isEnoughCommodity(orders,commodities);
        double sum=0;
        if(orderStatus==0){
            int i=0;
            for (Commodity commodity : commodities) {
                OrderBO orderBO = orders.get(i);
                double money = commodity.getDiscount()*commodity.getAmount();
                sum+=money*orderBO.getNumber();
                commodity.setInventory(commodity.getInventory()-orderBO.getNumber());
            }
            commodityService.updateBatchById(commodities);
        }
        Order order = new Order();
        order.setOrderStatus(orderStatus);
        order.setOrderType(0);
        order.setTheTotalAmountOfOrders(sum);
        BeanUtils.copyProperties(orderInfo,order);
        return order;
    }

    public ResultPageVo<Commodity> queryCommodityPageInfo(){
        List<Commodity> page = commodityService.list();
        return PageUtils.getPageInfo(page);
    }

    public Commodity queryCommodityById(long id){
        return commodityService.getById(id);
    }

    public boolean updateCommodityById(long id,String operator,String remark){
        Order byId = orderService.getById(id);
        if(byId==null) throw new RuntimeException("不存在该订单");
        if (redisService.exists("remain"+id))
        {
            int o = (int)redisService.get("remain" + id);
            redisService.del("remain"+id);
            byId.setOrderType(o);

        }else
        {
            Integer orderType = byId.getOrderType();
            redisService.set("remain"+id,orderType);
            byId.setOrderType(1);
        }
        OrderRecord orderRecord = new OrderRecord().setOperator(operator).setOrderType(byId.getOrderType())
                .setOrderStatus(byId.getOrderStatus())
                .setId(id)
                .setOperatingTime(new Date());
        orderRecordService.updateById(orderRecord);
        byId.setRemark(remark);
        return orderService.updateById(byId);

    }
}
